
s <- 1450

city_count <- readRDS("temp/city_count_pre_reg.rds") |> 
  filter(city != "washington")

city_count <- mutate(city_count,
                     across(c(n, pre_election, post_election), ~ (. / population) * 1000))

many_runs <- function(c){
  
  
  city_count$or <- runif(nrow(city_count))
  
  city_count <- dplyr::arrange(city_count, or)
  
  cities <- paste0(city_count$city[1:10], collapse = ", ")
  
  city_count <- dplyr::filter(dplyr::ungroup(city_count), dplyr::row_number() > 10)
  
  x1 <- summary(fixest::feols(post_election ~ nh_black + nh_white + share_dem +
                  median_age + median_income + some_college,
                city_count, vcov = "iid"))[["coeftable"]][2,4]
  
  x2 <- summary(fixest::feols(pre_election ~ nh_black + nh_white + share_dem +
                                median_age + median_income + some_college,
                              city_count, vcov = "iid"))[["coeftable"]][2,4]
  
  x3 <- summary(fixest::feols(n ~ nh_black + nh_white + share_dem +
                                median_age + median_income + some_college,
                              city_count, vcov = "iid"))[["coeftable"]][2,4]
  
return(data.frame(run = c,
                  post = x1,
                  pre = x2,
                  overall = x3,
                  cities_dropped = cities))
}

cl <- makeCluster(8)
clusterSetRNGStream(cl, s)
registerDoParallel(cl)

clusterExport(cl, list("many_runs", "city_count"))

vv <- rbindlist(parLapply(cl, c(1:10000),
                              fun = many_runs))

vv <- vv |> 
  pivot_longer(cols = c("pre", "post", "overall"))

ggplot(filter(vv, name == "post"), aes(x = value)) +
  geom_histogram(binwidth = 0.0001) +
  # facet_grid(name ~ .) +
  theme_bc() +
  scale_x_continuous(breaks = seq(0, 0.05, 0.01)) +
  scale_y_continuous(labels = scales::comma) +
  labs(x = "p-value", y = "Count",
       caption = "Regression controls for share white, Bident's vote share, median age, median income, and share with at least some college.")

ggsave("Output/Figures/rerun_histo.png",
       width = 6, height = 2, units = "in")
